import {
  getToken
} from './token'

const baseURL = HOST


export default function requset(method, url, params) {
  console.log(method, url, params)
  let data = {}
  // return '32'
  //   debugger
  const publicParams = {
    method: method.toLowerCase() || 'get',
    // openid: getToken() ,
    openid: "B123" ,
    // openid: "test123"
  }
  let api = `${baseURL}${url}`
  const allParams = {
    ...publicParams,
    ...(params || {})
  }
  if (method == 'get') {
    api = `${api}?${paramsToString(allParams)}`
  } else if (method == 'post') {
    data = allParams || {}
  }



  return new Promise((resolve, reject) => {
    wx.request({
      url: api,
      method: method.toUpperCase(),
      data,
      success(res) {
        console.log(res)
        resolve(res.data.data)
      },
      fail(e) {
        console.log(e)
      }
    })
  })

}


function paramsToString(params) {
  return Object.keys(params).map((key) => {
    const val = params[key]
    return Array.isArray(val) ? val.map((x) => {
      return composeKeyValue(key, x)
    }).join('&') : composeKeyValue(key, val)

  }).join('&')
}

function composeKeyValue(k, v, encode) {

  return encode === false ? `${k}=${v}` : `${encodeURIComponent(k)}=${encodeURIComponent(v)}`
}

export function getImage(id) {
  return `${baseURL}/api/oauth2/plugins/images/get.htm?id=${id}&w=400`
}
